#!/usr/bin/env bash
set -e
TEMPLATE_DIR="/home/cys/www/vector/template"
COMPONENT_DIR="/home/cys/www/vector/component"
VARS_DIR="/home/cys/www/vector/vars"
OUT_DIR="/home/cys/www/vector/generated"
mkdir -p "$OUT_DIR"
rm -rf  $OUT_DIR/*

# 获取非回环的IPv4地址并赋值
LOCAL_IP=$(ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}/\d+' | grep -v '^127.' | head -n 1 | cut -d '/' -f 1)

# 关键：导出变量使其在子进程中可用
export LOCAL_IP

# 输出结果验证
echo "当前IP地址: $LOCAL_IP"

if [ $LOCAL_IP == "172.29.151.175" ]; then
  VARS_DIR="/home/cys/www/vector/vars_175"
fi

for var in "$VARS_DIR"/*.yaml; do
  name=$(basename "$var" .yaml)
  # 把变量 export 成环境变量
  export $(xargs < "$var")
  # 渲染模板
  envsubst '$SOURCE_NAME $LOCAL_IP $BATCH_TIMEOUT_SECS $BATCH_EVENTS $READ_FROM_LOG $REQUEST_LIMIT_NUM $EXCLUDE_LOG  $LOG_DIR $CLICKHOUSE_TABLE' \
    < "$TEMPLATE_DIR/template.yaml" \
    > "$OUT_DIR/$name.yaml"

  envsubst '$SOURCE_NAME' \
      < "$COMPONENT_DIR/transform_mapper_key_inner_json.yaml" \
      > "$OUT_DIR/${name}_transform_mapper_key_inner_json.yaml"

  envsubst '$SOURCE_NAME $LOCAL_IP' \
        < "$COMPONENT_DIR/transform_parse_ip.yaml" \
        > "$OUT_DIR/${name}_transform_parse_ip.yaml"

  envsubst '$SOURCE_NAME' \
        < "$COMPONENT_DIR/transform_parse_json.yaml" \
        > "$OUT_DIR/${name}_transform_parse_json.yaml"

  envsubst '$SOURCE_NAME' \
        < "$COMPONENT_DIR/transform_parse_inner_json.yaml" \
        > "$OUT_DIR/${name}_transform_parse_inner_json.yaml"

  envsubst '$SOURCE_NAME' \
        < "$COMPONENT_DIR/transform_parse_outer_json.yaml" \
        > "$OUT_DIR/${name}_transform_parse_outer_json.yaml"

done

cp $COMPONENT_DIR/transform_general_promelog.yaml $OUT_DIR/

# 渲染prometheus模板
envsubst '$LOCAL_IP' \
    < "$TEMPLATE_DIR/prometheus.yaml" \
    > "$OUT_DIR/prometheus.yaml"

find $OUT_DIR/* -type f -exec sed -i 's/\r//' {} +
